#pragma once

#include <iostream>
#include <cstring>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <functional>

#include "Log.hpp"
#include "InetAddr.hpp"

using namespace log_ns;

static const int gsockfd = -1;
static const uint16_t glocalport = 8888;
static const int gblcklog = 8;

using command_service_t = std::function<void(int sockfd, InetAddr addr)>;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR
};

class TcpServer
{
public:
    TcpServer(command_service_t service, const uint16_t port = glocalport)
        : _listensockfd(gsockfd), _port(port), _isrunning(false), _service(service)
    {
    }

    class ThreadData
    {
    public:
        ThreadData(TcpServer *self, int sockfd, InetAddr &addr)
            : _self(self), _sockfd(sockfd), _addr(addr)
        {
        }
        ~ThreadData() {}

        TcpServer *_self;
        int _sockfd;
        InetAddr _addr;
    };

    void Init()
    {
        _listensockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(FATAL, "socket failed\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create success , sockfd : %d\n", _listensockfd);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(_listensockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind failed\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind create success\n");

        if (::listen(_listensockfd, gblcklog) < 0)
        {
            LOG(FATAL, "listen failed\n");
            exit(LISTEN_ERROR);
        }
        LOG(DEBUG, "listen create success\n");
    }

    void Loop()
    {
        // 忽略子进程返回信号，主进程就无需等待子进程
        // signal(SIGCHLD, SIG_IGN);
        _isrunning = true;
        while (_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            int sockfd = ::accept(_listensockfd, (struct sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept failed\n");
                continue;
            }
            InetAddr addr(client);
            LOG(DEBUG, "accept success , client info : %s\n", addr.AddrStr().c_str());

            // version 1
            //  pid_t id = fork();
            //  if (id == 0)
            //  {
            //      ::close(_listensockfd);
            //      if (fork() > 0)
            //          exit(0);
            //      Service(sockfd, addr);
            //      exit(0);
            //  }

            // ::close(sockfd);
            // int n = waitpid(id, nullptr, 0);
            // if (n > 0)
            // {
            //     LOG(INFO, "wait child success\n");
            // }

            // version 2
            pthread_t pid;
            ThreadData *td = new ThreadData(this, sockfd, addr);
            pthread_create(&pid, nullptr, Excute, nullptr);
        }
        _isrunning = false;
    }

    static void *Excute(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->_self->_service(td->_sockfd, td->_addr);
        ::close(td->_sockfd);
        delete td;
        return nullptr;
    }

    ~TcpServer() {}

private:
    int _listensockfd;
    uint16_t _port;
    bool _isrunning;
    command_service_t _service;
};